﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtDebug>
#include <QKeyEvent>
#include <QInputDialog>
#include <QMessageBox>
#include <string.h>

#include "SQLite.h"

#define TOTAL_MONEY (ui->totalAmountLabel->text().toDouble())

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 设置菜单栏跳转功能
    ui->stackedWidget->setCurrentIndex(0);
    ui->goodsAddWidget->setPageKind(true);
    ui->goodsUpdateWidget->setPageKind(false);
    connect(ui->salesMenu, SIGNAL(aboutToShow()), this, SLOT(changeToSalesSlot()));
    connect(ui->addAction, SIGNAL(triggered()), this, SLOT(changeToAddSlot()));
    connect(ui->updateAction, SIGNAL(triggered()), this, SLOT(changeToUpdateSlot()));

    // 初始化账单详细信息的列表
    initTableWidget();

    // 初始化快捷键列表
    initInstructionWidget();

    // 初始化数据库
    sqliteDB_open();

    // 开启子线程监听扫描器
    scanThread = new CodeScanThread(this);
    scanThread->start();

    kbdListenThread = new KeyboardListenThread(this);
    kbdListenThread->start();
}

MainWindow::~MainWindow()
{
    delete scanThread;
    delete kbdListenThread;
    delete ui;
}

void MainWindow::initTableWidget()
{
    // 设置账单信息表格的表头
    // 设置列宽之和为widget的宽度
    ui->tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 设置整行选中
    ui->tableWidget->setSelectionBehavior(QTableWidget::SelectRows);

    // 点击某行时，在goodsWidget_2显示该行的信息
    connect(ui->tableWidget, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(tableWidgetItemSelected(QTableWidgetItem*)));
}

void MainWindow::initInstructionWidget()
{
    // 整行选中
    ui->instructionWidget->setSelectionBehavior(QTableWidget::SelectRows);
    ui->instructionWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->instructionWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->instructionWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 接收SalesWidget的信号
    connect(ui->salesPage, SIGNAL(enterPressed()), this, SLOT(enterPressedSlot()));
    connect(ui->salesPage, SIGNAL(escPressed()), this, SLOT(escPressedSlot()));
    connect(ui->salesPage, SIGNAL(asteriskPressed()), this, SLOT(asteriskPressedSlot()));
    connect(ui->salesPage, SIGNAL(deletePressed()), this, SLOT(deletePressedSlot()));
    connect(ui->salesPage, SIGNAL(plusPressed()), this, SLOT(plusPressedSlot()));
}

void MainWindow::clearSalesInfo()
{
    ui->tableWidget->setRowCount(0);
    ui->nameLabel->setText("");
    ui->priceLabel->setText("0.00");
    ui->goodsAmountLabel->setText("0.00");
    ui->amountLabel->setText("0.00");
    ui->codeEdit->setText("");
    ui->totalAmountLabel->setText("0.00");
}

void MainWindow::deleteGoods(int row)
{
    // 只剩一行的话，可以直接情况账单信息
    int rows = ui->tableWidget->rowCount();
    if(rows == 1)
    {
        clearSalesInfo();
        return;
    }

    // 有多行的话，就默认选中下一行的商品
    int nextRow = (row + 1) % rows;
    ui->tableWidget->selectRow(nextRow);

    // 更新goods_widget的信息
    QTableWidgetItem* item = ui->tableWidget->item(row, 4);
    double amount = item->text().toDouble();
    double totalAmount = ui->totalAmountLabel->text().toDouble();
    ui->totalAmountLabel->setText(QString("%1").arg(totalAmount-amount));

    // 设置下一个选中的item
    item = ui->tableWidget->item(nextRow, 0);
    tableWidgetItemSelected(item);
    ui->tableWidget->setCurrentItem(item);
    ui->tableWidget->removeRow(row);
}

// 向账单中添加商品
void MainWindow::addGoods(Commodity comm)
{
    int row = ui->tableWidget->rowCount();
    bool isExisted = false;
    QTableWidgetItem* item = NULL;
    // 查找是否有相同id的商品
    for(int i=0; i<row; i++)
    {
        item = ui->tableWidget->item(i, 0);
        QString id = item->text();
        if(id == QString(comm.id))
        {
            isExisted = true;
            row = i;
            break;
        }
    }
    // 不存在就新添加一行
    if(!isExisted)
    {
        ui->tableWidget->insertRow(row);
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::fromLocal8Bit(comm.id)));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::fromLocal8Bit(comm.name)));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString("%1").arg(comm.price)));
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem("1"));
        ui->tableWidget->setItem(row, 4, new QTableWidgetItem(QString("%1").arg(comm.price)));
    }
    else
    {
        // 数量+1
        item = ui->tableWidget->item(row, 3);
        double num = item->text().toDouble();
        item->setText(QString("%1").arg(num+1));
        // 金额加上单价
        item = ui->tableWidget->item(row, 4);
        double amount = item->text().toDouble();
        item->setText(QString("%1").arg(amount+comm.price));
    }

    // 更新goodswidget信息
    // 设置选中当前商品
    item = ui->tableWidget->item(row, 0);
    tableWidgetItemSelected(item);
    ui->tableWidget->setCurrentItem(item);
    ui->totalAmountLabel->setText(QString("%1").arg(TOTAL_MONEY+comm.price));
}

bool MainWindow::isBillEmpty()
{
    return ui->tableWidget->rowCount()==0?true:false;
}

void MainWindow::tableWidgetItemSelected(QTableWidgetItem* item)
{
    int row = item->row();
    QTableWidgetItem* tmp;

    // 获取商品的条形码
    tmp = ui->tableWidget->item(row, 0);
    ui->codeEdit->setText(tmp->text());

    // 获取商品的名称
    tmp = ui->tableWidget->item(row, 1);
    ui->nameLabel->setText(tmp->text());

    // 获取商品的单价
    tmp = ui->tableWidget->item(row, 2);
    ui->priceLabel->setText(tmp->text());

    // 获取商品的数量
    tmp = ui->tableWidget->item(row, 3);
    ui->goodsAmountLabel->setText(tmp->text());

    // 获取商品的金额
    tmp = ui->tableWidget->item(row, 4);
    ui->amountLabel->setText(tmp->text());
}

void MainWindow::enterPressedSlot()
{
    // 结账
    qDebug() << "Total amount is " << TOTAL_MONEY;

    // 清空账单界面的信息
    clearSalesInfo();
}

void MainWindow::escPressedSlot()
{
    if(!isBillEmpty())
    {
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("请结束本次账单"));
        return;
    }
    qApp->quit();
}

void MainWindow::asteriskPressedSlot()
{
    QList<QTableWidgetItem*> itemList = ui->tableWidget->selectedItems();
    if(itemList.isEmpty())
        return;
    // 默认只能选择一个
    QTableWidgetItem* item = itemList.first();
    int row = item->row();
    QTableWidgetItem* goodsAmountItem = ui->tableWidget->item(row, 3);
    double goodsAmount = goodsAmountItem->text().toDouble();
    bool isOK = false;
    double newGoodsAmount = QInputDialog::getDouble(NULL, "更改数量", "请输入商品数量",
                                                goodsAmount, 0, 1000, 2, &isOK,
                                                Qt::MSWindowsFixedSizeDialogHint);  // 用于消除警告
    if(isOK)
    {
        // 如果数量是0，可以直接删除改行
        if(newGoodsAmount == 0)
        {
            deleteGoods(row);
            return;
        }
        // 更新tableWidget的内容
        goodsAmountItem->setText(QString("%1").arg(newGoodsAmount));
        QTableWidgetItem* priceItem = ui->tableWidget->item(row, 2);
        QTableWidgetItem* moneyItem = ui->tableWidget->item(row, 4);
        double oldMoney = moneyItem->text().toDouble();
        double newMoney = newGoodsAmount * priceItem->text().toDouble();
        moneyItem->setText(QString("%1").arg(newMoney));

        // 更新goods_widget的内容
        ui->goodsAmountLabel->setText(goodsAmountItem->text());
        ui->amountLabel->setText(moneyItem->text());
        ui->totalAmountLabel->setText(QString("%1").arg(TOTAL_MONEY-oldMoney+newMoney));
    }
}

void MainWindow::deletePressedSlot()
{
    QList<QTableWidgetItem*> itemList = ui->tableWidget->selectedItems();
    if(itemList.isEmpty())
        return;
    // 默认只能选择一个
    QTableWidgetItem* item = itemList.first();
    int row = item->row();
    deleteGoods(row);
}

void MainWindow::plusPressedSlot()
{
    static int noIdGoodsId = 0;         // 没有商品id的商品的初始id
    float defaultValue=0.00;            //默认值
    float minValue=0,maxValue=10000;    //最小、大值
    int decimals=2;                     //小数点后几位
    bool ok=false;
    double inputValue=QInputDialog::getDouble(this, QString::fromLocal8Bit("添加商品"), QString::fromLocal8Bit("请输入商品价格"),
                                             defaultValue, minValue, maxValue, decimals, &ok);
    if(ok)
    {
        Commodity comm;
        QString id = QString::fromLocal8Bit("未知商品%1").arg(noIdGoodsId++);
        char* str = id.toLocal8Bit().data();
        memcpy(comm.id, str, strlen(str));
        memcpy(comm.name, str, strlen(str));
        comm.price = inputValue;
        addGoods(comm);
    }
}

void MainWindow::changeToSalesSlot()
{
    ui->salesPage->grabKeyboard();
    ui->stackedWidget->setCurrentIndex(0);
    scanThread->start();
    kbdListenThread->start();
}

void MainWindow::changeToAddSlot()
{
    if(isBillEmpty())
    {
        ui->stackedWidget->setCurrentIndex(1);
        ui->salesPage->releaseKeyboard();       // 解除键盘监听，否则所有的消息都会被salesPage拦截
        scanThread->stop();                     // 关闭扫描器监听线程
        kbdListenThread->stop();
    }
    else
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("请结束本次账单"));
}

void MainWindow::changeToUpdateSlot()
{
    if(isBillEmpty())
    {
        ui->salesPage->releaseKeyboard();
        ui->stackedWidget->setCurrentIndex(2);
        scanThread->stop();                     // 关闭扫描器监听线程
        kbdListenThread->stop();
    }
    else
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("请结束本次账单"));
}

void MainWindow::on_ensureButton_add_clicked()
{
    Commodity comm = ui->goodsAddWidget->getCmmodity();
    if(strcmp(comm.id, "")==0 || strcmp(comm.name, "")==0)
    {
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("请填写完整信息"));
        return;
    }

    sqliteDB_opt_add(comm.name, comm.id, comm.price);
    ui->goodsAddWidget->clearInfo();
}


void MainWindow::on_cancelButton_add_clicked()
{
    ui->goodsAddWidget->clearInfo();
}


void MainWindow::on_ensureButton_update_clicked()
{
    Commodity comm = ui->goodsUpdateWidget->getCmmodity();
    if(strcmp(comm.id, "")==0 || strcmp(comm.name, "")==0)
    {
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("请填写完整信息"));
        return;
    }
    sqliteDB_opt_delete_by_id(comm.id);
    sqliteDB_opt_add(comm.name, comm.id, comm.price);
    ui->goodsUpdateWidget->clearInfo();
}

void MainWindow::on_cancelButton_update_clicked()
{
    ui->goodsUpdateWidget->clearInfo();
}

void MainWindow::on_deleteButton_update_clicked()
{
    Commodity comm = ui->goodsUpdateWidget->getCmmodity();
    if(strcmp(comm.id, "")==0 || strcmp(comm.name, "")==0)
    {
        QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("请填写完整信息"));
        return;
    }
    sqliteDB_opt_delete_by_id(comm.id);
}

